﻿using Sodu.Entity;
using Sodu.SoduConstants;
using Sodu.UC;
using Sodu.Util;
using Sodu.Util.HttpHelper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkID=390556 上有介绍

namespace Sodu.Pages
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class Page_Loaded : Page
    {
        /// <summary>
        /// 普通的列表
        /// </summary>
        public List<BookEntity> BookEntityList;

        /// <summary>
        /// BookShelfEntityList
        /// </summary>
        public List<BookEntity> BookShelfEntityList;

        public Page_Loaded()
        {
            this.InitializeComponent();

            //   this.NavigationCacheMode = NavigationCacheMode.Required;

            if (SoduContantsValue.IfLogin)
            {
                this.btnUser.Content = SoduContantsValue.UserName;
            }
        }

        /// <summary>
        /// 在此页将要在 Frame 中显示时进行调用。
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。
        /// 此参数通常用于配置页。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
            GetHomeData();
        }

        /// <summary>
        /// 离开时取消返回事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
        }

        async private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
        {
            e.Handled = true;
            if (!Frame.CanGoBack)
            {
                var dig = new MessageDialog("确定要退出Sodu?", "确认");
                var btnOk = new UICommand("是");
                dig.Commands.Add(btnOk);
                var btnCancel = new UICommand("否");
                dig.Commands.Add(btnCancel);

                var result = await dig.ShowAsync();
                if (null != result && result.Label == "是")
                {
                    Application.Current.Exit();
                }
            }
            else
            {
                Frame.GoBack();
            }
        }

        /// <summary>
        /// 获取首页数据,并赋值
        /// </summary>
        /// <param name="html"></param>
        public void GetHomeData()
        {
            SetControlVisibilaty(1);

            string uri = SoduConstants.SoduContantsValue.HomePage;
            HttpHelper.HttpGetRequest(uri, GetDataCompleted);
        }

        /// <summary>
        /// 获取数据结束
        /// </summary>
        /// <param name="html"></param>
        async public void GetDataCompleted(string html)
        {
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
            {
                try
                {
                    if (string.IsNullOrEmpty(html))
                    {
                        throw new Exception();
                    }
                    else
                    {
                        SetData(html);
                    }
                }
                catch (Exception ex)
                {
                    Exceptionhandle();

                }
            }
                 );
        }

        /// <summary>
        /// 当获取数据异常时调用
        /// </summary>
        public void Exceptionhandle()
        {
            this.pnlListUpdate.Children.Clear();
            this.pnlListBookShelf.Children.Clear();

            BookEntity t_entity = new BookEntity() { BookName = "网络错误", ChapterName = "暂无数据" };
            UC_BookListItem t_item = new UC_BookListItem(t_entity);
            t_item.IsEnabled = false;

            this.pnlListUpdate.Children.Add(t_item);

            MessageBox.Show("获取数据失败，请重试。");
        }

        /// <summary>
        /// 为界面赋值
        /// </summary>
        /// <param name="html"></param>
        public void SetData(string html)
        {
            try
            {
                this.pnlListBookShelf.Children.Clear();
                this.pnlListUpdate.Children.Clear();

                //已登录
                if (html.Contains("id=\"form2\"") && html.Contains("注销") && html.Contains("站长留言"))
                {
                    BookShelfEntityList = GetBookEntitykList.GetBookShelfListFromHtml(html);
                    //  UserName = GetBookEntitykList.GetUserNameFromHtml(html);
                    if (BookShelfEntityList != null && BookShelfEntityList.Count > 0)
                    {
                        UC_BookListItem t_item;
                        for (int i = 0; i < BookShelfEntityList.Count; i++)
                        {
                            t_item = new UC_BookListItem(BookShelfEntityList[i]);
                            this.pnlListBookShelf.Children.Add(t_item);
                        }
                    }
                }

                BookEntityList = GetBookEntitykList.GetBookEntitykListFromHtml(html);
                if (BookEntityList != null && BookEntityList.Count > 0)
                {
                    UC_BookListItem t_item;
                    for (int i = 0; i < BookEntityList.Count; i++)
                    {
                        t_item = new UC_BookListItem(BookEntityList[i]);
                        this.pnlListUpdate.Children.Add(t_item);
                    }
                }
            }

            catch (Exception ex)
            {
                Exceptionhandle();
            }
            finally
            {
                SetControlVisibilaty(2);
            }
        }

        /// <summary>
        /// 移除书架
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {

            List<BookEntity> t_list = new List<BookEntity>();

            UC_BookListItem t_item;
            for (int i = 0; i < this.pnlListBookShelf.Children.Count; i++)
            {

                t_item = (UC_BookListItem)this.pnlListBookShelf.Children[i];
                if (t_item.Checked == true)
                {
                    t_list.Add(t_item.Entity);
                }
            }

            if (t_list.Count == 0)
            {
                MessageBox.Show("您没有选择需要下架的书。");
            }
            else
            {
                string s = string.Empty;
                for (int i = 0; i < t_list.Count; i++)
                {
                    s += t_list[i].BookName + "  ";
                }
                MessageBox.Show(s);
            }
        }

        /// <summary>
        /// 刷新当前页面数据
        /// </summary>
        private void RefreshData()
        {
            GetHomeData();
        }



        #region  公共方法



        /// <summary>
        ///   1 加载中  2 加载完成
        /// </summary>
        /// <param name="flag"></param>
        public void SetControlVisibilaty(int flag = -1)
        {

            ///加载中
            if (flag == 1)
            {
                this.progress.Visibility = Visibility.Visible;
                this.pnlContent.Visibility = Visibility.Collapsed;
            }

            ///加载完成
            else if (flag == 2)
            {
                this.progress.Visibility = Visibility.Collapsed;
                this.pnlContent.Visibility = Visibility.Visible;
            }
        }

        /// 点击回车
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Page_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
            {
                if (FocusManager.GetFocusedElement() == this.txtSearchPara)
                {
                    btnSearch_Click(null, null);
                }
            }
        }

        /// <summary>
        /// 点击搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.txtSearchPara.Text))
            {
                MessageBox.Show("请输入搜索关键字");
                return;
            }
            Frame.Navigate(typeof(Page_SearchResult), new SearchParameterEntity(this.txtSearchPara.Text, 1));
        }


        /// <summary>
        /// 点击注销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogout_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(MainPage), "logout");
        }

        /// <summary>
        /// 点击用户名进入书架
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUser_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Page_BookShelf));
        }

        /// <summary>
        /// 点击图片logo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            RefreshData();
        }

        #endregion
    }
}


